﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Web;
using System.Xml;
using System.ServiceModel.Syndication;
using Ninject;
using Ninject.Web;
using NLog;
using OBoobsWallpaper.Data;
using OBoobsWallpaper.Entity;
using OBoobsWallpaper.Logic;

namespace OBoobsWallpaper
{
    public partial class Default : PageBase
    {
        private const string RssUrl = "Default.aspx?op=rss";
        private const string FileName = "oBoobs.theme";
        private static readonly Logger Logger = LogManager.GetCurrentClassLogger();

        [Inject]
        public IRssLoader RssLoader { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            Logger.Trace("Request from user {0} url:{1}", Request.UserHostAddress, Request.Url.Query);
            if (string.Compare(Request.QueryString["op"], "rss", true) == 0)
                ReturnRss();
            else
                ReturnThemeFile();
        }

        private string GetSiteRootPath()
        {
            return Request.Url.GetLeftPart(UriPartial.Authority) + VirtualPathUtility.ToAbsolute("~/");
        }

        private void ReturnThemeFile()
        {
            var fileBody = Resource.oBoobs.Replace("$RSS_URL$", Path.Combine(GetSiteRootPath(), RssUrl));

            Response.Clear();
            Response.ContentEncoding = Encoding.UTF8;
            Response.ContentType = "application/octet-stream";
            Response.AddHeader("Content-Disposition", "attachment; filename=" + FileName);
            //Response.Headers["Content-Length"] = Encoding.UTF8.GetByteCount(fileBody).ToString();

            Response.Output.Write(fileBody);

            Response.End();
        }

        private void ReturnRss()
        {
            Response.Clear();
            Response.ContentEncoding = Encoding.UTF8;
            Response.ContentType = "text/xml";

            WriteRss(Response.Output, RssLoader.LoadRss());

            Response.End();
        }

        private static void WriteRss(TextWriter output, Rss rss)
        {
            var feed = new SyndicationFeed
                           {
                               Title = new TextSyndicationContent("OBoobs windows wallpapers"),
                               Copyright = new TextSyndicationContent("I © 2010"),
                               Description = new TextSyndicationContent("The most exiting wallpapers for real guy"),
                               Generator = "RSS Feed Generator",
                               Id = "www.oboobs.ru",
                               LastUpdatedTime = rss.LastUpdateTime
                           };
            var link = new SyndicationLink
                           {
                               Title = "OBoobs.ru", 
                               Uri = new Uri("http://oboobs.ru")
                           };
            feed.Links.Add(link);

            var feedItems = new List<SyndicationItem>();
            foreach (var item in rss.RssItems)
            {
                var feedItem = new SyndicationItem
                                   {
                                       Id = item.Id,
                                       Title = new TextSyndicationContent(item.Title),
                                   };
                feedItem.Links.Add(SyndicationLink.CreateSelfLink(new Uri(item.ImageLink)));
                feedItem.Links.Add(SyndicationLink.CreateMediaEnclosureLink(new Uri(item.ImageLink), "image/JPG", 0));
                feedItems.Add(feedItem);
            }
            feed.Items = feedItems;

            var rssWriter = XmlWriter.Create(output);
            if (rssWriter == null)
                throw new NullReferenceException();
            var rssFormatter = new Rss20FeedFormatter(feed);
            rssFormatter.WriteTo(rssWriter);
            rssWriter.Close();
        }
    }
}